package com.hxzy.controller.front.merchandiser;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.vo.resp.PageResp;
import com.hxzy.common.vo.resp.R;
import com.hxzy.controller.front.mapstruct.MerchandiserConvert;
import com.hxzy.controller.front.merchandiser.req.MerchandiserAddReq;
import com.hxzy.controller.front.merchandiser.req.MerchandiserEditReq;
import com.hxzy.controller.front.merchandiser.req.MerchandiserIdReq;
import com.hxzy.controller.front.merchandiser.req.MerchandiserReq;
import com.hxzy.controller.front.merchandiser.resp.EnterpriseProcessResp;
import com.hxzy.controller.front.merchandiser.resp.MerchandiserResp;
import com.hxzy.entity.EnterpriseProcess;
import com.hxzy.entity.Merchandiser;
import com.hxzy.service.EnterpriseProcessService;
import com.hxzy.service.MerchandiserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Desc 描述
 * @Author: admin
 * @Date: 2023/07/10/15:15
 */
@Api(tags = "前端-商家API")
@RestController
@RequestMapping(value = "/front/enterprise")
public class FrontMerchandiserController {

    /**
     * 商家
     */
    @Autowired
    private MerchandiserService merchandiserService;

    /**
     * 历史审核记录
     */
    @Autowired
    private EnterpriseProcessService  enterpriseProcessService;

    @ApiOperation(value = "商家注册")
    @PostMapping(value = "/add")
    public R register(@RequestBody @Valid MerchandiserAddReq req){
        // 验证号码是否已经注册过了
        LambdaQueryWrapper<Merchandiser> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Merchandiser::getLoginName, req.getLoginName());
        long count=this.merchandiserService.count(queryWrapper);
        if(count>0){
            return R.build(AckCode.EXISTS_VALUE);
        }

        Merchandiser entity = MerchandiserConvert.INSTANCE.convert(req);
        entity.setLoginPwd(BCrypt.hashpw(entity.getLoginPwd()));
        entity.setStatus("0");
        entity.setCreateBy(entity.getLoginName());

        boolean save = this.merchandiserService.save(entity);
        return save? R.ok(): R.build(AckCode.DATABASE_ERROR);
    }


    @ApiOperation(value = "查询审核记录")
    @GetMapping(value = "/process/{loginName}")
    public R historyProcess( @PathVariable(value = "loginName") String loginName){
        if(StrUtil.isBlank(loginName)){
            return R.build(AckCode.SYSTEM_PARAM_FAIL);
        }

        //检查格式对不对
        final String  regex="^0?(13|15|17|18|14|19)[0-9]{9}$";
        //创建表达式
        Pattern pattern = Pattern.compile(regex);
        //创建匹配模型
        Matcher matcher = pattern.matcher(loginName);
        if(!matcher.matches()){
            return R.build(AckCode.ENTERPRISE_PHONE_ERROR);
        }

       //merchandiser
        LambdaQueryWrapper<Merchandiser> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Merchandiser::getLoginName, loginName);
        Merchandiser db = this.merchandiserService.getOne(queryWrapper);
        if(Objects.isNull(db)){
            return R.build(AckCode.NOT_FOUND_DATA);
        }

        //返回给前端的
        Map<String,Object> dataMap=new HashMap<>();
        dataMap.put("merchandiser", MerchandiserConvert.INSTANCE.convert(db));

        //enterpriseProcessList  历史审核记录
        List<EnterpriseProcessResp> enterpriseProcessList= this.enterpriseProcessService.findHistoryByTenantId(db.getId());
        //是否要添加正在审核中的状态
        if(db.getStatus().equals("0")){
            EnterpriseProcessResp  resp=new EnterpriseProcessResp();
            //模拟一个主键
            resp.setId(IdUtil.getSnowflakeNextId());
            resp.setTenantId(db.getId());
            resp.setStatus("0");
            //第一次提交
            if(Objects.isNull(db.getUpdateTime())){
                resp.setCreateTime( db.getCreateTime());
            }else {
                resp.setCreateTime(db.getUpdateTime());
            }
            resp.setDescription("审核中，请耐心等待...");

            enterpriseProcessList.add(0, resp);
        }

        dataMap.put("enterpriseProcessList",enterpriseProcessList);

        return R.okHasData(dataMap);
    }

    @ApiOperation(value = "商家重新提交申请资料")
    @PutMapping(value = "/update")
    public R resubmitRegister(@RequestBody @Valid MerchandiserEditReq req){
        // 审核状态是未通过才能
        Merchandiser db = this.merchandiserService.getById(req.getId());
        if(db==null){
            return R.build(AckCode.NOT_FOUND_DATA);
        }
        if(db.getStatus().equals("0")){
            return R.build(AckCode.ENTERPROSE_NOT_MODIFY);
        }

        //为了防止用户恶意攻击你
        if(!db.getLoginName().equals(req.getLoginName())){
            return R.build(AckCode.NOT_FOUND_DATA);
        }

        //复制修改的数据
        Merchandiser convert = MerchandiserConvert.INSTANCE.convert(req);
        convert.setStatus("0");
        convert.setUpdateBy(req.getLoginName());
        boolean result = this.merchandiserService.updateById(convert);
        return  result?R.ok():R.build(AckCode.DATABASE_ERROR);
    }

    @ApiOperation(value = "分页查询")
    @GetMapping(value = "/data")
    public R<PageResp<MerchandiserResp>> search(@Valid MerchandiserReq req){
        PageInfo<MerchandiserResp> pageInfo=this.merchandiserService.frontSearch(req);

        PageResp<MerchandiserResp>  resp=new PageResp<>();
        resp.setTotal(pageInfo.getTotal());
        resp.setRows(pageInfo.getList());
        return R.okHasData(resp);
    }


    @ApiOperation(value = "根据id查询")
    @GetMapping(value = "/findById")
    public R<MerchandiserResp> findById(@Valid MerchandiserIdReq req){
        MerchandiserResp resp= this.merchandiserService.findById(req);
        if(resp==null){
            return R.build(AckCode.NOT_FOUND_DATA);
        }

        return R.okHasData(resp);
    }





}
